import React, { useState, useEffect } from 'react';
import { Row, Col, Typography, Button, Image, Descriptions, Tag, message, Spin } from 'antd';
import { ShoppingCartOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { getProductById, Product } from '../../services/product.service';
import { isAuthenticated } from '../../utils/auth';

const { Title, Paragraph } = Typography;

const ProductDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [product, setProduct] = useState<Product | null>(null);

  useEffect(() => {
    if (id) {
      fetchProductDetail(parseInt(id));
    }
  }, [id]);

  const fetchProductDetail = async (productId: number) => {
    try {
      setLoading(true);
      const data = await getProductById(productId);
      setProduct(data);
    } catch (error) {
      console.error('Failed to fetch product details:', error);
      message.error('获取商品详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleBuyNow = () => {
    if (!isAuthenticated()) {
      message.warning('请先登录');
      navigate('/login');
      return;
    }
    
    // In a real application, this would navigate to checkout or add to cart
    message.success('商品已加入购物车');
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!product) {
    return <div>商品不存在或已下架</div>;
  }

  return (
    <div className="product-detail">
      <Row gutter={[32, 32]}>
        <Col xs={24} md={12}>
          <Image
            src={product.imageUrl}
            alt={product.name}
            style={{ width: '100%', maxHeight: '500px', objectFit: 'contain' }}
          />
        </Col>
        <Col xs={24} md={12}>
          <Title level={2}>{product.name}</Title>
          <div style={{ margin: '16px 0' }}>
            <Tag color="blue">{product.category}</Tag>
          </div>
          <div style={{ margin: '16px 0' }}>
            <span style={{ color: '#f50', fontSize: 24, fontWeight: 'bold' }}>
              ¥{product.price.toFixed(2)}
            </span>
          </div>
          <Paragraph style={{ fontSize: 16, marginBottom: 24 }}>
            {product.description}
          </Paragraph>
          <div style={{ margin: '24px 0' }}>
            <Button 
              type="primary" 
              size="large" 
              icon={<ShoppingCartOutlined />} 
              onClick={handleBuyNow}
              disabled={product.stock <= 0}
              style={{ marginRight: 16 }}
            >
              立即购买
            </Button>
            <Button size="large">加入购物车</Button>
          </div>
          <Descriptions bordered column={1} style={{ marginTop: 24 }}>
            <Descriptions.Item label="商品编号">{product.id}</Descriptions.Item>
            <Descriptions.Item label="库存状态">
              {product.stock > 0 ? (
                <Tag color="green">有货 ({product.stock})</Tag>
              ) : (
                <Tag color="red">无货</Tag>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="上架时间">{product.createdAt}</Descriptions.Item>
          </Descriptions>
        </Col>
      </Row>
    </div>
  );
};

export default ProductDetail;